<template>
  <div class="DigitalCollationAdd">
    <div class="form-card">
      <div class="card-title">数字著录</div>
      <div class="card-line"></div>
      <div class="card-steps">
        <ApproveProcess code="A0578" />
      </div>
      <!-- <div class="card-tip">
        <img
          src="@/assets/images/meeting_add_tip.png"
          alt=""
        />
        <span>
          {{ hint }}
        </span>
      </div> -->
      <div class="form-content">
        <NScrollbar>
          <NSpin :show="false">
            <n-form
              ref="formRef"
              :model="formData"
              :rules="rules"
              label-placement="left"
              label-width="auto"
              require-mark-placement="right-hanging"
              class="form-container"
            >
              <n-grid :cols="2">
                <n-grid-item>
                  <n-form-item
                    label="类型"
                    path="type"
                  >
                    <n-select
                      v-model:value="formData.type"
                      :options="typeOptions"
                    />
                  </n-form-item>
                </n-grid-item>
                在
                <n-grid-item>
                  <n-form-item
                    label="著作类型"
                    path="workType"
                  >
                    <div
                      class="type-name"
                      @click="handletype"
                    >
                      {{ formData.workType ? formData.workType : '选择格式' }}
                    </div>
                  </n-form-item>
                </n-grid-item>
              </n-grid>
              <div class="form-line"></div>
              <div v-if="shouldRender">
                <n-grid :cols="2">
                  <n-grid-item
                    v-for="field in formFields"
                    :key="field.key"
                  >
                    <n-form-item
                      :label="field.label"
                      :path="field.key"
                    >
                      <n-input
                        v-if="field.key.includes('FileName') || field.key.includes('Location')"
                        v-model:value="formData[field.key]"
                      />
                      <n-input-number
                        v-else-if="field.key.includes('fileSize')"
                        :default-value="0"
                        :min="0"
                        :show-button="false"
                        v-model:value="formData[field.key]"
                      >
                        <template #suffix>MB</template>
                      </n-input-number>
                      <n-date-picker
                        v-else-if="
                          field.key === 'collectionTime' || field.key === 'retentionPeriod'
                        "
                        v-model:value="formData[field.key]"
                        type="date"
                      />
                      <n-select
                        v-else-if="field.key === 'securityLevel'"
                        v-model:value="formData[field.key]"
                        :options="securityLevelOptions"
                      />
                      <n-input
                        v-else-if="field.key === 'contentDescription' || field.key === 'remarks'"
                        v-model:value="formData[field.key]"
                        type="textarea"
                      />
                      <n-upload
                        :max="1"
                        :custom-request="(e: any) => commonUpload(e)"
                        :on-remove="handleRemove"
                        :default-file-list="tasmpList"
                        directory-dnd
                        v-else-if="field.key === 'attachment'"
                      >
                        <n-upload-dragger>
                          <div class="upload-container">
                            <n-icon
                              size="41"
                              :depth="3"
                            >
                              <CloudUpload />
                            </n-icon>
                            <n-text style="font-size: 12px; color: #326c53">
                              点击或将文件拖拽到这上传
                            </n-text>
                          </div>
                        </n-upload-dragger>
                      </n-upload>
                      <n-input
                        v-else
                        v-model:value="formData[field.key]"
                      />
                    </n-form-item>
                  </n-grid-item>
                </n-grid>
              </div>
            </n-form>
          </NSpin>
        </NScrollbar>
      </div>
    </div>
    <div class="form-bottom">
      <div class="btn-list">
        <n-button @click="handleCanel">取消</n-button>
        <n-button @click="handleSubmit">暂存</n-button>
        <n-button
          type="primary"
          @click="handleSubmit"
        >
          确定
        </n-button>
      </div>
    </div>
    <NModal
      :auto-focus="false"
      v-model:show="typeModalVisiable"
    >
      <div class="custom-modal type-modal">
        <div class="modal-title">
          <span>请选择类型</span>
          <img
            src="@/assets/images/meeting_dialog_close.png"
            alt=""
            @click="typeModalVisiable = false"
          />
        </div>
        <div class="modal-container">
          <div class="type-list">
            <div
              class="type-item"
              v-for="(item, index) in typeList"
              :key="item.value"
              :style="{
                backgroundImage: `url(${getAssetUrl(`DigitalCollation/type${index + 1}.png`)})`
              }"
              @click="handletypeClick(item)"
            >
              <span>{{ item.label }}</span>
            </div>
          </div>
        </div>
      </div>
    </NModal>
    <NModal
      :auto-focus="false"
      v-model:show="matterModalVisiable"
    >
      <div class="custom-modal matter-modal">
        <div class="modal-title">
          <span>请选择关联实物</span>
          <img
            src="@/assets/images/meeting_dialog_close.png"
            alt=""
            @click="matterModalVisiable = false"
          />
        </div>
        <div class="modal-container">
          <div class="matter-list">
            <div
              class="matter-item"
              v-for="(item, index) in matterList"
              :key="item.value"
              @click="handleMatterClick(item)"
            >
              <img
                :src="getAssetUrl(`DigitalCollation/matter${index + 1}.png`)"
                alt=""
              />
              <span>{{ item.label }}</span>
            </div>
          </div>
        </div>
      </div>
    </NModal>
    <IncludedModal
      v-model:show="includedModalVisible"
      @select="handleIncludedSelect"
      @reset="handleIncludedReset"
      @cancel="handleIncludedCancel"
      @submit="handleIncludedSubmit"
    />
    <NotIncludedModal
      v-model:show="notIncludedModalVisible"
      @select="handleNotIncludedSelect"
      @reset="handleNotIncludedReset"
      @cancel="handleNotIncludedCancel"
      @submit="handleNotIncludedSubmit"
    />
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  onMounted,
  onUnmounted,
  onUpdated,
  onBeforeUpdate,
  watch,
  computed,
  nextTick
} from 'vue'
import {
  useMessage,
  NScrollbar,
  type FormRules,
  type UploadCustomRequestOptions,
  NUploadDragger
} from 'naive-ui'
import IncludedModal from './components/IncludedModal.vue'
import NotIncludedModal from './components/NotIncludedModal.vue'

import dayjs from 'dayjs'
import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { getAssetUrl } from '@/utils/common'
import ApproveProcess from '@/components/Approve/approveProcess.vue'
import { useTagStore } from '@/stores/layout'
import { CloudUpload } from '@vicons/ionicons5'
import {
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NSelect,
  NDatePicker,
  NUpload,
  NButton,
  NSpace,
  NGrid,
  NGridItem,
  NSpin,
  NIcon,
  NModal
} from 'naive-ui'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const formRef1 = ref(null)
const message = useMessage()
const initialState = {
  // 通用字段
  type: null,
  workType: '文本',
  flowNumber: '',
  registrationNumber: '',
  assetIdentifier: '',
  versionName: '',
  subject: '',
  collectionName: '',
  collectionCode: '',

  // 文本/其他特有字段
  contentDescription: '',
  retentionPeriod: null,
  securityLevel: null,
  fileName: '',
  fileSize: null,
  formatName: '',
  author: '',
  source: '',
  storageLocation: '',
  originalVector: '',
  note: '',
  attachment: null,

  // 图像特有字段
  collector: '',
  collectionTime: null,
  recordingEquipment: null,
  assetNumber: '',

  // 音频/视频特有字段
  duration: ''
}
const formData = ref({ ...initialState })

const formFields = computed(() => {
  const commonFields = [
    { label: '流水号', key: 'flowNumber' },
    { label: '登记号', key: 'registrationNumber' },
    { label: '资产标识符/条码号', key: 'assetIdentifier' },
    { label: '版本名称', key: 'versionName' },
    { label: '主题词', key: 'subject' },
    { label: '中华版本收藏主体名称', key: 'collectionName' },
    { label: '中华版本收藏主体编码', key: 'collectionCode' }
  ]

  const specificFields = {
    文本: [
      { label: '内容描述', key: 'contentDescription' },
      { label: '保管期限', key: 'retentionPeriod' },
      { label: '密级', key: 'securityLevel' },
      { label: '计算机文件名', key: 'fileName' },
      { label: '计算机文件大小', key: 'fileSize' },
      { label: '格式名称', key: 'formatName' },
      { label: '著录者', key: 'author' },
      { label: '来源', key: 'source' },
      { label: '存储地址', key: 'storageLocation' },
      { label: '原始载体', key: 'originalVector' },
      { label: '备注', key: 'note' },
      { label: '附件', key: 'attachment' }
    ],
    图像: [
      { label: '采集者', key: 'collector' },
      { label: '采集时间', key: 'collectionTime' },
      { label: '保管期限', key: 'retentionPeriod' },
      { label: '密级', key: 'securityLevel' },
      { label: '拍摄设备', key: 'recordingEquipment' },
      { label: '计算机文件名', key: 'fileName' },
      { label: '计算机文件大小', key: 'fileSize' },
      { label: '格式名称', key: 'formatName' },
      { label: '著录者', key: 'author' },
      { label: '来源', key: 'source' },
      { label: '存储地址', key: 'storageLocation' },
      { label: '原始载体', key: 'originalVector' },
      { label: '实物资产号', key: 'assetNumber' },
      { label: '备注', key: 'note' },
      { label: '附件', key: 'attachment' }
    ],
    音频: [
      { label: '采集者', key: 'collector' },
      { label: '采集时间', key: 'collectionTime' },
      { label: '时间长度', key: 'duration' },
      { label: '内容描述', key: 'contentDescription' },
      { label: '保管期限', key: 'retentionPeriod' },
      { label: '密级', key: 'securityLevel' },
      { label: '摄录设备', key: 'recordingEquipment' },
      { label: '计算机文件名', key: 'fileName' },
      { label: '计算机文件大小', key: 'fileSize' },
      { label: '格式名称', key: 'formatName' },
      { label: '著录者', key: 'author' },
      { label: '来源', key: 'source' },
      { label: '存储地址', key: 'storageLocation' },
      { label: '原始载体', key: 'originalVector' },
      { label: '备注', key: 'note' },
      { label: '附件', key: 'attachment' }
    ],
    视频: [
      { label: '采集者', key: 'collector' },
      { label: '采集时间', key: 'collectionTime' },
      { label: '时间长度', key: 'duration' },
      { label: '内容描述', key: 'contentDescription' },
      { label: '保管期限', key: 'retentionPeriod' },
      { label: '密级', key: 'securityLevel' },
      { label: '摄录设备', key: 'recordingEquipment' },
      { label: '计算机文件名', key: 'fileName' },
      { label: '计算机文件大小', key: 'fileSize' },
      { label: '格式名称', key: 'formatName' },
      { label: '著录者', key: 'author' },
      { label: '来源', key: 'source' },
      { label: '存储地址', key: 'storageLocation' },
      { label: '原始载体', key: 'originalVector' },
      { label: '备注', key: 'note' },
      { label: '附件', key: 'attachment' }
    ],
    其他: [
      { label: '内容描述', key: 'contentDescription' },
      { label: '保管期限', key: 'retentionPeriod' },
      { label: '密级', key: 'securityLevel' },
      { label: '计算机文件名', key: 'fileName' },
      { label: '计算机文件大小', key: 'fileSize' },
      { label: '格式名称', key: 'formatName' },
      { label: '著录者', key: 'author' },
      { label: '来源', key: 'source' },
      { label: '存储地址', key: 'storageLocation' },
      { label: '原始载体', key: 'originalVector' },
      { label: '备注', key: 'note' },
      { label: '附件', key: 'attachment' }
    ]
  }

  return [...commonFields, ...(specificFields[formData.value.workType] || [])]
})
const rules = ref<FormRules>({
  type: {
    required: true,
    message: '请选择类型',
    trigger: ['blur', 'change']
  },
  workType: {
    required: true,
    message: '请选择著作类型',
    trigger: ['blur', 'change']
  },
  assetIdentifier: {
    required: true,
    message: '请输入资产标识符/条码号',
    trigger: ['blur', 'input']
  },
  versionName: {
    required: true,
    message: '版本名称',
    trigger: ['blur', 'input']
  },
  fileName: {
    required: true,
    message: '请输入计算机文件名',
    trigger: ['blur', 'input']
  },
  fileSize: {
    required: true,
    type: 'number',
    message: '请输入计算机文件大小',
    trigger: ['blur', 'change']
  },
  formatName: {
    required: true,
    message: '请输入格式名称',
    trigger: ['blur', 'input']
  },
  storageLocation: {
    required: true,
    message: '请输入存储地址',
    trigger: ['blur', 'input']
  },
  duration: {
    required: true,
    message: '请输入时间长度',
    trigger: ['blur', 'input']
  }
})

const typeOptions = ref([
  {
    label: '实物版本的数字化版本',
    value: 'type1'
  },
  {
    label: '纯数字版本',
    value: 'type2'
  }
])

const securityLevelOptions = [{ label: '请选择', value: null }]

const formatCurrency = (value: number | null) => {
  if (value === null) return ''
  return `${value.toLocaleString('en-US')} MB`
}

const typeModalVisiable = ref(false)
const handletype = () => {
  typeModalVisiable.value = true
}

const typeList = ref([
  {
    label: '文本',
    value: 'type1'
  },
  {
    label: '音频',
    value: 'type2'
  },
  {
    label: '图像',
    value: 'type3'
  },
  {
    label: '视频',
    value: 'type4'
  },
  {
    label: '其他',
    value: 'type5'
  }
])

const shouldRender = ref(true)
const forceRerender = () => {
  shouldRender.value = false
  nextTick(() => {
    shouldRender.value = true
  })
}
const handletypeClick = (e: any) => {
  formData.value.workType = e.label
  typeModalVisiable.value = false
  forceRerender()
}

const matterModalVisiable = ref(false)
const matterList = ref([
  {
    label: '已入藏藏品',
    value: 'matter1'
  },
  {
    label: '未入藏藏品',
    value: 'matter2'
  }
])
const handleMatterClick = (e: any) => {
  matterModalVisiable.value = false
  if (e.value === 'matter1') {
    includedModalVisible.value = true
  } else if (e.value === 'matter2') {
    notIncludedModalVisible.value = true
  }
}

const includedModalVisible = ref(false)

const handleIncludedSelect = (formData: any) => {
  // 处理查询逻辑
}

const handleIncludedReset = () => {
  // 处理重置逻辑
}

const handleIncludedCancel = () => {
  // 处理取消逻辑
}

const handleIncludedSubmit = (formData: any) => {
  // 处理提交逻辑
  router.push({
    path: '/OA/DigitalCollation/DigitalCollections'
  })
}

const notIncludedModalVisible = ref(false)

const handleNotIncludedSelect = (formData: any) => {
  // 处理查询逻辑
}

const handleNotIncludedReset = () => {
  // 处理重置逻辑
}

const handleNotIncludedCancel = () => {
  // 处理取消逻辑
}

const handleNotIncludedSubmit = (formData: any) => {
  // 处理提交逻辑
  router.push({
    path: '/OA/DigitalCollation/DigitalCollections'
  })
}

const fileConfig = computed(() => {
  switch (formData.value.workType) {
    case '文本':
      return {
        fileHZ: ['doc', 'docx', 'pdf', 'txt'],
        uploadTip: '请上传文本文件 (doc, docx, pdf, txt)'
      }
    case '图像':
      return {
        fileHZ: ['jpg', 'png', 'jpeg', 'gif'],
        uploadTip: '请上传图片文件 (jpg, png, jpeg, gif)'
      }
    case '音频':
      return {
        fileHZ: ['mp3', 'wav', 'ogg'],
        uploadTip: '请上传音频文件 (mp3, wav, ogg)'
      }
    case '视频':
      return {
        fileHZ: ['mp4', 'avi', 'mov'],
        uploadTip: '请上传视频文件 (mp4, avi, mov)'
      }
    default:
      return {
        fileHZ: ['jpg', 'png', 'jpeg', 'pdf', 'doc', 'docx'],
        uploadTip: '请上传支持的文件类型'
      }
  }
})
const tasmpList = ref<any>([])
const commonUpload = async ({
  file,
  onFinish,
  onError,
  onProgress
}: UploadCustomRequestOptions) => {
  const tmp = file.name.split('.')
  const fileExtension = tmp[tmp.length - 1].toLowerCase()
  if (!fileConfig.value.fileHZ.includes(fileExtension)) {
    message.error(fileConfig.value.uploadTip)
    onError()
    return
  }

  const fileData = new FormData()
  fileData.append('file', file.file as File)
  const [error, res] = await sendRequest({
    module: 'upload',
    api: 'uploadFile',
    override: {
      data: fileData,
      onUploadProgress(v: any) {
        onProgress({ percent: Math.ceil(v.progress) })
      }
    }
  })
  if (error) {
    message.error(error.message)
    onError()
    return
  }
  if (res.code !== 0) {
    message.error('上传失败')
    onError()
    return
  }
  tasmpList.value.push({
    id: res.data.fileId,
    name: res.data.name,
    status: 'finished',
    url: res.data.url
  })
  message.success('上传成功')
  onFinish()
}

// 删除
const handleRemove = ({ file }: any) => {
  const index = tasmpList.value.findIndex((it: any) => it.name == file.name)
  tasmpList.value.splice(index, 1)
  message.success('删除成功')
  // returnPictures()
  return true
}

watch(
  () => tasmpList.value,
  () => {
    formData.value.image = tasmpList.value[0]?.url
  },
  {
    deep: true
  }
)
const handleSubmit = (e: MouseEvent) => {
  e.preventDefault()
  formRef.value?.validate((errors) => {
    if (!errors) {
      if (formData.value.type === 'type1') {
        matterModalVisiable.value = true
        // 这里可以添加提交表单的逻辑
      } else {
        message.success('表单提交成功')
      }
    } else {
      message.error('请填写所有必填字段')
      // matterModalVisiable.value = true
    }
  })
}
const handleReset = () => {
  Object.keys(initialState).forEach((key) => {
    formData.value[key] = initialState[key]
  })
}

const handleCanel = () => {
  router.back() // 返回上一页
}

onMounted(async () => {
  //   getWorkFlow()
})
watch(
  () => route.path,
  async () => {
    formData.value.type = route.query.formType
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.DigitalCollationAdd {
  position: relative;
  width: 100%;
  height: 100%;
}
.form-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
  overflow: hidden;
  padding: 20px;
  background: #e1e1e1;
  .card-title {
    display: flex;
    align-items: center;
    width: 100%;
    height: 34px;
    color: #1d2129;
    font-size: 24px;
    font-weight: 500;
    line-height: 34px;
    &::before {
      content: '';
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 7px;
      border-radius: 2.5px;
      background: #6cb187;
    }
  }
  .card-line {
    width: 100%;
    height: 1px;
    margin-top: 16px;
    background-color: #fff;
  }
  .card-steps {
    width: 100%;
    // display: flex;
    // justify-content: flex-start;
    margin: 20px;
    // margin-left: 200px;
  }
  .card-tip {
    display: flex;
    width: 880px;
    margin: 20px 0;
    padding: 4px 8px;
    justify-content: center;
    align-items: center;
    gap: 8px;
    border-radius: 8px;
    background: #f3f8f2;
    color: #4e5969;
    font-size: 14px;
    line-height: 34px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    img {
      width: 16px;
      height: 16px;
    }
    span {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .form-content {
    display: flex;
    justify-content: center;
    width: 100%;
    height: calc(100% - 195px);
    padding-top: 41px;
    .form-container {
      padding: 0 100px;
      .form-line {
        width: 100%;
        height: 0px;
        margin-bottom: 24px;
        border-top: 1px dashed #f1f2f4;
      }
      .type-name {
        display: flex;
        width: 102px;
        height: 32px;
        padding: 0px 12px;
        justify-content: center;
        align-items: center;
        border-radius: 2px;
        border: 1px solid #0b8d61;
        background: #fff;
        color: #0b8d61;
        font-size: 12px;
        line-height: 22px;
        cursor: pointer;
      }
      .upload-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10px;
        width: 100%;
        height: 100%;
        padding: 4px 4px;
      }
    }
  }
}
.form-bottom {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 55px;
  border-top: 1px solid #f7f8f9;
  //   background: #f0efee;
  background: #ffffff;
  z-index: 999;
  .btn-list {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 24px;
    width: 100%;
    height: 100%;
    padding-right: 20px;
  }
}
.type-modal {
  width: 1252px;
  height: 395px;
  .type-list {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    .type-item {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 16px;
      width: 208.1px;
      height: 107px;
      // border: 1px solid #00895b;
      cursor: pointer;
      background-size: cover;
      background-repeat: no-repeat;
      &:hover {
      }
      img {
        width: 100%;
        height: 100%;
      }
      span {
        color: #1d2129;
        font-size: 24px;
        font-weight: 600;
      }
    }
  }
}
.matter-modal {
  width: 480px;
  height: 240px;
  .matter-list {
    display: flex;
    gap: 76px;
    .matter-item {
      display: inline-flex;
      padding: 8px 17px;
      justify-content: center;
      align-items: center;
      gap: 8px;
      border-radius: 2px;
      border: 1px solid #326c53;
      background: rgba(66, 143, 110, 0.28);
      color: #326c53;
      font-size: 14px;
      line-height: 24px; /* 171.429% */
      cursor: pointer;
      img {
        width: 24px;
        height: 24px;
      }
    }
  }
}
:deep(.n-form-item) {
  display: grid;
  grid-template-columns: 1fr 1fr;
  justify-items: end;
  margin-bottom: 20px;
}
:deep(.n-form-item-blank) {
  width: 328px;
}
:deep(.n-form-item-feedback-wrapper:not(:empty)) {
  width: 100%;
}
:deep(.n-upload-trigger--image-card) {
  display: flex;
  width: 160px;
  height: 90px;
  justify-content: space-between;
  align-items: center;
}
</style>
